package org.example.myleet.p384;

/**
 * Fisher-Yates洗牌算法
 */
public class Solution2 {

    private int n;
    private int[] originNums;
    private int[] shuffledNums;

    public Solution2(int[] nums) {
        n = nums.length;
        originNums = nums;
        reset();
    }

    public int[] reset() {
        if (null == shuffledNums) {
            shuffledNums = new int[n];
        }
        System.arraycopy(originNums, 0, shuffledNums, 0, n);
        return shuffledNums;
    }

    public int[] shuffle() {
        for (int i = 0; i < n; ++i) {
            int j = (int) Math.floor(Math.random() * (n - i)) + i;
            int t = shuffledNums[i];
            shuffledNums[i] = shuffledNums[j];
            shuffledNums[j] = t;
        }
        return shuffledNums;
    }
}
